package com.zige.zige.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.zige.zige.R;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.dialog.PromptDialog;
import com.zige.zige.pojo.UserInfo;
import com.zige.zige.pojo.VideoTags;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.SharedPreferencesUtils;
import com.zige.zige.utils.SystemUtils;
import com.zige.zige.utils.ToastUtils;
import com.zige.zige.view.MyGridView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by Fei on 2016/3/9.
 */
public class UserSelectVideoTagsActivity extends BaseActivity {

    private Activity activity;
    private Button btn_commit;

    Adapter adapter = new Adapter();
    private ArrayList<VideoTags> mList = new ArrayList<>();
    private MyGridView gridView;
    private boolean press = true;
    private String uId, userAcount, userPassword;
    private String babyName, babySex, babybirthday;
    private String headImagePath, headImageName, headImageUrl;

    private int textColorType;

    private TextView tv_title;
    private LinearLayout lay_back;

    private boolean isCoimplete = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏

        setContentView(R.layout.activity_userselectvideotags);
        activity = this;

        uId = getIntent().getStringExtra("uerId");
        userAcount = getIntent().getStringExtra("userName");
        userPassword = getIntent().getStringExtra("userPassword");
        headImageName = getIntent().getStringExtra("headImageName");
        headImagePath = getIntent().getStringExtra("headImagePath");
        headImageUrl = getIntent().getStringExtra("headImageUrl");
        babyName = getIntent().getStringExtra("babyName");
        babySex = getIntent().getStringExtra("babySex");
        babybirthday = getIntent().getStringExtra("babybirthday");
        getVideoTags();
        initGridView();

    }

    private ArrayList<VideoTags> getListItems() {
        return mList;
    }

    private void initGridView() {
        tv_title = serchViewById(R.id.title_name);
        tv_title.setText("资料完善");
        lay_back = serchViewById(R.id.lay_back);
        lay_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_commit = serchViewById(R.id.btn_commit);
        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (textTags == null || textTags.equals("")) {
                    showErrorDialog("宝贝喜欢的视频类型未选择");
                    return;
                }
                if (headImageUrl == null || headImageUrl.equals("")) {
                    sendBabyInfo();
                } else {
                    getQiNiuToken();
                }
            }
        });
        lay_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCoimplete) {
                    back2Main();
                }
                finish();
            }
        });
        gridView = serchViewById(R.id.gridView);
        gridView.requestFocus();
        gridView.setAdapter(adapter);

    }


    private void getVideoTags() {
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(null, activity, UrlConsts.VIDEO_TAGS) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    String msg = object.getString("message");
                    if (code == 0000) {
                        closeLoadingDialog();
                        JSONArray array = object.getJSONArray("tagList");
                        int size = array.length();
                        for (int i = 0; i < size; i++) {
                            JSONObject jsonObject = array.getJSONObject(i);
                            VideoTags videoTags = new VideoTags();
                            videoTags.parsefromJSON(jsonObject.toString());
                            getListItems().add(videoTags);
                        }
                    } else {
                        throw new Exception(msg);
                    }
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                    ToastUtils.showToast(activity, e.getMessage());
//                    tv_check_error.setVisibility(View.VISIBLE);
                } finally {
                    closeLoadingDialog();
                }
            }
        });
    }

    String textTags;

    private class Adapter extends BaseAdapter {
        final Map<Integer, String> map = new HashMap<Integer, String>();

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = View.inflate(activity, R.layout.gridview_videotype_item, null);
                viewHolder.tv_type = (Button) convertView.findViewById(R.id.tv_type);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            VideoTags videoTags = mList.get(position);
            viewHolder.tv_type.setText(videoTags.videoTags);

            viewHolder.tv_type.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    press = !viewHolder.tv_type.isSelected();
                    if (press) {
                        int[] type = {1, 2, 3, 4, 5};
                        textColorType = (int) (Math.random() * type.length) + 1;
                        viewHolder.tv_type.setSelected(true);
                        viewHolder.tv_type.setTextColor(getResources().getColor(R.color.white));
                        if (textColorType == 1) {
                            viewHolder.tv_type.setBackgroundResource(R.drawable.videotags_btn_select_blue);
                            String bu = viewHolder.tv_type.getText().toString();
                            map.put(position, bu);
                        } else if (textColorType == 2) {
                            viewHolder.tv_type.setBackgroundResource(R.drawable.videotags_btn_select_orange);
                            String bu = viewHolder.tv_type.getText().toString();
                            map.put(position, bu);
                        } else if (textColorType == 3) {
                            viewHolder.tv_type.setBackgroundResource(R.drawable.videotags_btn_select_pink);
                            String bu = viewHolder.tv_type.getText().toString();
                            map.put(position, bu);
                        } else if (textColorType == 4) {
                            viewHolder.tv_type.setBackgroundResource(R.drawable.videotags_btn_select_yellow);
                            String bu = viewHolder.tv_type.getText().toString();
                            map.put(position, bu);
                        } else if (textColorType == 5) {
                            viewHolder.tv_type.setBackgroundResource(R.drawable.videotags_btn_select_darkblue);
                            String bu = viewHolder.tv_type.getText().toString();
                            map.put(position, bu);
                        } else {
                            viewHolder.tv_type.setBackgroundResource(R.drawable.videotags_btn_normal);
                            viewHolder.tv_type.setTextColor(getResources().getColor(R.color.videotags_text));
                            String bu = viewHolder.tv_type.getText().toString();
                            map.put(position, bu);
                        }

                    } else {
                        viewHolder.tv_type.setBackgroundResource(R.drawable.videotags_btn_normal);
                        viewHolder.tv_type.setTextColor(getResources().getColor(R.color.color_6A6A6A));
                        viewHolder.tv_type.setSelected(false);
                        map.remove(position);
                    }

                    textTags = (map.values().toString()).replace("[", "").replace("]", "");

                }
            });

            return convertView;
        }
    }

    class ViewHolder {
        Button tv_type;
    }


    /**
     * 获取七牛token
     */

    private void getQiNiuToken() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("fileKey", headImageName);
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(params, activity, UrlConsts.GET_QINIU_TOKEN) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    if (code == 0000) {
                        String qiNiuToken = object.getString("qiniuToken");
                        UploadManager uploadManager = new UploadManager();
                        uploadManager.put(headImagePath, headImageName, qiNiuToken, new UpCompletionHandler() {
                            @Override
                            public void complete(String s, ResponseInfo responseInfo, JSONObject jsonObject) {
                                if (200 == responseInfo.statusCode) {
                                    sendBabyInfo();
                                } else {
                                    closeLoadingDialog();
                                    showErrorDialog("上传图像失败，请重新提交");
                                }
                            }
                        }, null);

                    } else {
                        closeLoadingDialog();
                        showErrorDialog("网络异常，上传失败");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 完善资料请求服务器保存
     */
    private void sendBabyInfo() {

        HashMap<String, String> parmas = new HashMap<>();
        parmas.put("uid", uId);
        parmas.put("childName", babyName);
        parmas.put("childSex", babySex);
        parmas.put("childBirthday", babybirthday);
        parmas.put("tags", textTags);
        parmas.put("iconUrl", headImageUrl == null ? "" : headImageUrl);
        showLoadingDialog();
        TaskExecutor.getInstance().execute(new PostRequestTask(parmas, activity, UrlConsts.PERFECT_BABYINFOR) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    String msg = object.getString("message");
                    if (code == 0000 || code == 0) {
                        SharedPreferencesUtils.saveValue(UserSelectVideoTagsActivity.this, SharedPreferencesUtils.user_complete_infomation, true);
                        isCoimplete = true;
                        showDialog();
                    } else {
                        throw new Exception(msg);
                    }
                } catch (Exception e) {

                } finally {
                    closeLoadingDialog();
                }
            }
        });
    }

    private void userLogin() {
        String type = "0";
        String deviceId = SystemUtils.getDeviceKey(activity).trim();
        String pushKey = JPushInterface.getRegistrationID(getApplicationContext());
        HashMap<String, String> parms = new HashMap<String, String>();
        parms.put("loginType", type);
        parms.put("account", userAcount);
        parms.put("password", userPassword);
        parms.put("deviceId", deviceId);
        parms.put("pushKey", pushKey);
        TaskExecutor.getInstance().execute(new PostRequestTask(parms, activity, UrlConsts.USER_LOGIN) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    String msg = object.getString("message");
                    closeLoadingDialog();
                    if (code == 0000) {
                        UserInfo userInfo = new UserInfo();
                        userInfo.parsefromJSON(object.getString("userInfo"));
                        application.setUserInfo(userInfo);
                        SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.keep_login_state, true);
                        SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.keep_login_userCount, userAcount);
                        SharedPreferencesUtils.saveValue(activity, SharedPreferencesUtils.keep_login_password, userPassword);
                        closeLoadingDialog();
                        isCoimplete = true;
                        new Handler() {
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                                showDialog();
                            }
                        }.sendEmptyMessageDelayed(1, 500);
                    } else {
                        closeLoadingDialog();
                        throw new Exception(msg);
                    }
                } catch (Exception e) {
                    showErrorDialog(e.getMessage());
                } finally {
                    closeLoadingDialog();
                }
            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isCoimplete) {
                back2Main();
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }

    private void back2Main() {
        startActivity(new Intent(activity, HomedActivity.class));
        finish();
        overridePendingTransition(R.anim.r2l_in, R.anim.r2l_out);
    }

    private void showDialog() {
        PromptDialog dialog = new PromptDialog();
        dialog.setContextString("注册完成，前去登录！");
        dialog.setDialogLister(new PromptDialog.DialogLister() {
            @Override
            public void clickTrue() {
                startActivity(new Intent(activity, RegisterActivity.class));
                finish();
                overridePendingTransition(R.anim.r2l_in, R.anim.r2l_out);
            }
        });
        dialog.show(getFragmentManager(), "dialo");

//        LayoutInflater inflater = getLayoutInflater();
//        View layout = inflater.inflate(R.layout.register_completer_dialog, null);
//
//        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
//        builder.setView(layout);
//        builder.setPositiveButton("前去登录", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//                startActivity(new Intent(activity, RegisterActivity.class));
//                finish();
//                overridePendingTransition(R.anim.r2l_in, R.anim.r2l_out);
//            }
//        });
//        builder.create().show();
    }
}
